<template>
  <!--  面包屑导航-->
  <el-breadcrumb separator=">">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>

  <!-- 卡片区域 -->
  <el-card>
    <!--    添加角色-->
    <el-row>
      <el-col :span="4">
        <el-button type="primary" @click="addRoleVisible = true">添加角色</el-button>
      </el-col>
    </el-row>
    <!--角色列表-->
    <el-table :data="rolesList" border stripe>
      <el-table-column type="expand">
        <template v-slot="scope">
          <!--          渲染一级权限-->
          <el-row :class="['bdbottom', i1 === 0? 'bdtop': '', 'vcenter']" v-for="(item1, i1) in scope.row.children"
                  :key="item1.id">
            <el-col :span="5">
              <el-tag @close="removeRights(scope.row, item1.id)" class="mx-1" closable effect="dark">
                {{ item1.authName }}
              </el-tag>
              <i class="iconfont icon-youjiantou"></i>
            </el-col>
            <!--      渲染二级和三级权限        -->
            <el-col :span="19">
              <el-row :class="[i2 === 0? '': 'bdtop', 'vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                <el-col :span="5">
                  <el-tag @close="removeRights(scope.row, item2.id)" class="mx-1" type="success" closable effect="dark">
                    {{ item2.authName }}
                  </el-tag>
                  <i class="iconfont icon-youjiantou"></i>
                </el-col>
                <!--                渲染三级权限-->
                <el-col :span="19">
                  <el-tag @close="removeRights(scope.row, item3.id)" class="mx-1" v-for="item3 in item2.children"
                          :key="item3.id" type="warning" closable effect="dark">
                    {{ item3.authName }}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <!--          <pre>-->
          <!--            {{scope.row}}-->
          <!--          </pre>-->
        </template>
      </el-table-column>
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button size="small" type="primary" class="iconfont icon-edit" @click="openEditRoleDialog(scope.row.id)">
            编辑
          </el-button>
          <el-button size="small" type="success" class="iconfont icon-delete"
                     @click="openDeleteMessageBox(scope.row.id)">删除
          </el-button>
          <el-button size="small" type="warning" class="iconfont icon-setting" @click="openDistibuteRightsDialog(scope.row)">
            分配权限
          </el-button>
          <!--        {{scope.row}}-->
        </template>
      </el-table-column>
    </el-table>
    <!--添加角色对话框-->
    <el-dialog v-model="addRoleVisible" title="添加角色" @close="addRoleDialogClosed">
      <el-form ref="addRoleRef" :rules="addRoleRules" :model="addRoleForm" label-width="120px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancellAddRoleDialog">取消</el-button>
        <el-button type="primary" @click="confirmAddRoleDialog">确认</el-button>
      </span>
      </template>
    </el-dialog>
    <!--编辑角色对话框-->
    <el-dialog v-model="editRoleVisible" title="添加角色" @close="editRoleDialogClosed">
      <el-form ref="editRoleRef" :rules="addRoleRules" :model="editRoleForm" label-width="120px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancellEditRoleDialog">取消</el-button>
        <el-button type="primary" @click="confirmEditRoleDialog">确认</el-button>
      </span>
      </template>
    </el-dialog>
    <!--    分配权限对话框-->
    <el-dialog v-model="distibuteRightsVisible" title="分配权限"  @close="closeDistrivuteRightsDialog">
      <el-tree :data="allRightsTreeList" :props="rightsProps" ref="allRightsTreeListRef" node-key="id" :default-checked-keys="dck" show-checkbox default-expand-all />
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="distibuteRightsVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDistributeRightsDialog">确认</el-button>
      </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import {AllRoles, AddRole, EditRole, SelectRoleById, DeleteRole, DeleteRoleRights,AllRightsByTree, SetRoleRights} from "@/api";
import {reactive, Ref, ref} from "vue";
import {ElForm, ElMessage, ElMessageBox} from "element-plus";
// 获取角色列表
const rolesList = ref([])
const getRolesList = async () => {
  const {data: res} = await AllRoles()
  // console.log(res)
  if (res.meta.status !== 200) {
    return ElMessage.error('获取角色列表失败')
  }
  rolesList.value = res.data
}
getRolesList()
// 添加角色对话框
const addRoleVisible = ref(false)
const addRoleForm = reactive({
  roleName: '',
  roleDesc: ''
})
const addRoleRules = ref({
  roleName: [
    {required: true, message: '请输入角色名称', trigger: 'blur'},
    {min: 3, max: 10, message: '角色名称长度在3~10个字符', trigger: 'blur'}
  ],
  roleDesc: [
    {required: true, message: '请输入角色描述', trigger: 'blur'},
    {min: 5, max: 20, message: '角色描述长度在5~20个字符', trigger: 'blur'}
  ]
})
// const addRoleRef = ref<InstanceType<typeof ElForm>|undefined>()
const addRoleRef: any = ref(null)
// const addRoleRef = ref<InstanceType<typeof ElForm>>()
// const addRoleRef = ref <undefined>()
// const addRoleRef: any = ref(null)
// 关闭添加角色对话框重置表单
const addRoleDialogClosed = () => {
  addRoleRef.value.resetFields()
}
// 取消添加角色对话框
const cancellAddRoleDialog = () => {
  addRoleVisible.value = false
}
// 确认添加角色对话框
const confirmAddRoleDialog = async () => {
  const {data: res} = await AddRole(addRoleForm)
  if (res.meta.status !== 201) {
    return ElMessage.error('添加角色失败')
  }
  ElMessage.success('添加角色成功')
  // 重新获取数据
  getRolesList()
  addRoleVisible.value = false
}
// 编辑角色信息对话框
const editRoleRef: any = ref(null)
const editRoleVisible = ref(false)
let editRoleForm = reactive({
  id: 0,
  roleName: '',
  roleDesc: ''
})
// 打开编辑角色信息对话框
const openEditRoleDialog = async (id: number) => {
  const {data: res} = await SelectRoleById(id)
  console.log(res)
  if (res.meta.status !== 200) {
    return ElMessage.error('获取角色信息失败')
  }
  editRoleForm.id = res.data.roleId;
  editRoleForm.roleName = res.data.roleName;
  editRoleForm.roleDesc = res.data.roleDesc;
  editRoleVisible.value = true
}
//确认编辑角色信息框
const confirmEditRoleDialog = async () => {
  const {data: edit_res} = await EditRole(editRoleForm.id, {
    roleName: editRoleForm.roleName,
    roleDesc: editRoleForm.roleDesc
  })
  if (edit_res.meta.status !== 200) {
    return ElMessage.error('更新角色信息失败')
  }
  ElMessage.success('更新角色信息成功')
  //重新获取角色信息列表
  getRolesList()
  editRoleVisible.value = false
}
// 取消编辑角色信息框
const cancellEditRoleDialog = () => {
  editRoleVisible.value = false
}
//关闭编辑角色信息框，重置表单信息
const editRoleDialogClosed = () => {
  editRoleRef.value.resetFields()
}
//删除角色信息操作
const openDeleteMessageBox = (id: number) => {
  ElMessageBox.confirm(
      '将永久删除角色信息，是否继续？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const {data: res} = await DeleteRole(id)
        console.log(res)
        if (res.meta.status !== 200) {
          return ElMessage.error('删除失败')
        }
        //重新获取角色列表
        getRolesList()
        ElMessage.success('已成功删除')
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })

}
//删除角色指定权限
const removeRights = (role: any, rightId: number) => {
  console.log('role.children')
  console.log(role.children)
  ElMessageBox.confirm(
      '将永久删除角色权限，是否继续？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const {data: res} = await DeleteRoleRights(role.id, rightId)
        console.log(res)
        if (res.meta.status !== 200) {
          return ElMessage.error('删除失败')
        }
        //重新获取角色权限
        role.children = res.data
        ElMessage.success('已成功删除')
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
}
//分配权限操作
const distibuteRightsVisible = ref(false)
//获取所有权限树形图
const allRightsTreeList = ref([])
const rightsProps = {
  children: 'children',
  label: 'authName',
  disabled: 'disabled',
}
//存放当前角色的权限id
const dck = ref([])
//获取当前角色的所有权限的id
const getCheckedRights = (node: any, chRighs:Ref[])=>{
  if(!node.children){return chRighs.push(node.id)}
  node.children.forEach((item:any) => {return getCheckedRights(item, chRighs)})
}
//当前角色的id
const currentRoleId = ref(0)
//打开分配权限对话框
const openDistibuteRightsDialog = async (node: any)=>{
  currentRoleId.value = node.id
  getCheckedRights(node, dck.value)
  const {data: res} = await AllRightsByTree()
  if(res.meta.status !== 200) {return ElMessage.error('获取所有权限失败')}
  allRightsTreeList.value = res.data
  distibuteRightsVisible.value = true
}
//获取当前选中的所有节点
const allRightsTreeListRef: any = ref(null)

// 确认分配权限对话框
const confirmDistributeRightsDialog = async ()=>{
  const currentCheckedRights = [
    ...(allRightsTreeListRef.value.getCheckedKeys()),
    ...(allRightsTreeListRef.value.getHalfCheckedKeys()),
  ]
  const rids: string = currentCheckedRights.join(',')
  const {data: res} = await SetRoleRights(currentRoleId.value, rids)
  if(res.meta.status !== 200){return ElMessage.error('分配角色权限失败')}
  getRolesList()
  ElMessage.success('成功分配角色权限')
  distibuteRightsVisible.value = false
}
//关闭分配权限对话框
const closeDistrivuteRightsDialog = ()=>{
  //清空dck
  dck.value = []
  currentRoleId.value = 0
}

</script>

<style lang="less" scoped>

.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #e1dcdc;
}

.bdbottom {
  border-bottom: 1px solid #e1dcdc;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
